package Filter;

import java.io.IOException;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import BeenChina.PM.Model.ModelUser;
import BeenChina.PM.Model.ModelUserRole;
import BeenChina.PM.Service.ServiceFactory;
import BeenChina.PM.Util.CookieUtil;
import BeenChina.PM.Util.Permission;

public class LoginFilter extends HttpServlet implements Filter
{
	private static final long serialVersionUID = 1L;

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException {
		
				 HttpServletRequest request = (HttpServletRequest) sRequest;      
		         HttpServletResponse response = (HttpServletResponse) sResponse;      
		         HttpSession session = request.getSession();      
		         String url=request.getServletPath();  
		         String contextPath=request.getContextPath();
		         
		         if(url.equals("")) url+="/"; 
		         
		         //if((url.startsWith("/")&&!url.startsWith("/jspPage/login")&&!url.startsWith("/head") )){
		         if((url.startsWith("/") 		        		 
		        		 &&!url.startsWith("/login")
		        		 &&!url.startsWith("/jspPage/login") 
		        		 &&!url.startsWith("/css/") 
		        		 &&!url.startsWith("/img/")
		        		 &&!url.startsWith("/js/")
		        		 && !url.startsWith("/basePage/") 
		        		 && !url.startsWith("/index")
		        		 )){
		             		        	 
		        	 ModelUser  user=(ModelUser)session.getAttribute("user");
		        	 if(user==null){
		        		 user = CookieUtil.getCookie(request);	
		        		 if (user!=null){ 
		        			 System.out.println("get user fom cookie and update permissions ");
		        			 String userPermissions = getPerimissions(user.getId());		        		
			        		 if (userPermissions.length()>0){		        				 
			        			user.setAllpermissions(userPermissions.split(","));
			        		  }else {
			        			user.setAllpermissions(null);
			        		 }
		        		 } 
		        		 session.setAttribute("user", user);		        	 
		        	 }
		        	 
		              if(user==null){
		            	   String s= "window.top.location.href ='" + contextPath + "/login.action'";
		            	   response.getWriter().println("<script language=javascript>"+ s + "</script>");
		                   //response.sendRedirect(contextPath+"/jspPage/login.jsp");
		            	   return;
		              }
		              else{
		            	  String key= ServiceFactory.getInstance().getSystemInfoService().getSessionId(user.getUserID());		            	 
		            	  if (!key.toLowerCase().equals(user.getSessionId().toLowerCase())){
		            		  String s= "window.top.location.href ='" + contextPath + "/login!loginFromCookie.action'";
		            		  response.getWriter().println("<script language=javascript>"+ s + "</script>");
		            		  return;
		            		  //response.sendRedirect(contextPath+"/jspPage/login.jsp");
		            	 }
		            	 else {
		            		 //add  action log
		            		 if (url.endsWith("action")){
		            			 
		            			// String aString= request.getParameter("dateFrom");
		            			 String searchParam ="";
		            			 Enumeration<String> enumeration = request.getParameterNames();
		            				while (enumeration.hasMoreElements()) {
		            					String parameterName = (String) enumeration.nextElement();
		            					//System.out.println("Parameter = " + parameterName);
		            					searchParam += parameterName + ":"  +request.getParameter(parameterName) + ";";
		            				}
		            			// System.out.print(searchParam);
		            			 
		            			 String accessIP = getIpAddr(request);
		            			 String action = url.substring(1); 
		            			 String actionName = Permission.getActionName(action);
		            			 ServiceFactory.getInstance().getCommonInfoService().insertActionLog(user.getUserID(),action,actionName,accessIP,searchParam);
		            		 }
		            		 
		            		 request.getSession().setAttribute("userID", user.getUserID());
		            		 request.getSession().setAttribute("userName", user.getUserName());
		            		 request.getSession().setAttribute("locale", getIpAddr(request));
						 }
		              }
		         }  
		         filterChain.doFilter(sRequest, sResponse);    		
	}
		
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub	 
		
	}	
	
	private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	
	private String getPerimissions(String userID)
	{
		String userPermissions ="";
		
		List<ModelUserRole> userRoles = ServiceFactory.getInstance().getSystemInfoService().selectUserRoles(userID);		
		if (userRoles != null){
			for (ModelUserRole modelUserRole : userRoles) {				
			String permissionIds = modelUserRole.getPermissionsString();
			EnumSet<Permission> permissions = Permission.getPremissions(permissionIds);
			
			if (permissions!=null){ 
			
				if (userPermissions.length()>0)
					userPermissions+= ",";
					userPermissions += permissionIds;
					}
			}
		}
		return userPermissions;
	}
	
}